<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <!-- <el-form-item label="编号" prop="number">
              <el-input v-model="queryParams.number" placeholder="请输入编号" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="领用时间" prop="arrivalTime" style="width: 308px">
              <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item label="类别" prop="type">
              <el-select v-model="queryParams.type" placeholder="请选择使用类型" clearable>
                <el-option v-for="dict in adm_item_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="审批状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
                <el-option v-for="dict in approval_record_status" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="applyTime" style="width: 308px">
              <el-date-picker v-model="createTimeRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item label="物品名称" prop="itemName">
                <el-select v-model="queryParams.itemId" placeholder="请选择使用类型" clearable>
                  <el-option v-for="dict in select_item_list" :key="dict.id" :label="dict.itemName" :value="dict.id" />
                </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['system:admItemReceive:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['system:admItemReceive:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['system:admItemReceive:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['system:admItemReceive:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="admItemReceiveList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="领用人" align="center" prop="useId">
          <template #default="scope">
            {{ scope.row.useName }}
          </template>
        </el-table-column>
        <el-table-column label="申请部门" align="center" prop="deptId">
          <template #default="scope">
            <el-tag type="primary" disable-transitions>
              {{ scope.row.deptName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="类别" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="adm_item_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="物品名称" align="center" prop="itemName" />
        <el-table-column label="领用数量" align="center" prop="amount" />
        <el-table-column label="单位" align="center" prop="unit" />
        <el-table-column label="用途" align="center" prop="purpose">
          <template #default="scope">
            <el-tooltip :content="scope.row.purpose" placement="top" :disabled="!scope.row.remark">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.purpose }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="审批状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="approval_record_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" width="100">
          <template #default="scope">
            <el-tooltip :content="scope.row.remark" placement="top" :disabled="!scope.row.remark">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.remark }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <template v-if="!hasFinalPermission">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:admItemReceive:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['system:admItemReceive:remove']"></el-button>
              </el-tooltip>
              <el-tooltip content="部门审核" placement="top" v-if="!['2', '4'].includes(scope.row.status)">
                <el-button link type="primary" icon="CircleCheck" @click="handleAudit(scope.row)"
                  v-hasPermi="['administration:item:audit']"></el-button>
              </el-tooltip>
            </template>
            <el-tooltip content="董办审核" placement="top" v-if="['1', '2', '4'].includes(scope.row.status)">
              <el-button link type="primary" icon="CircleCheck" @click="handleFinalAudit(scope.row)"
                v-hasPermi="['administration:seal:final']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改物品领用对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" ref="dialogRef" width="900px" append-to-body
      class="seal-dialog" @opened="handleDialogOpen">
      <template #default>
        <el-form ref="admItemReceiveFormRef" :model="form" :rules="rules" label-width="140px" label-position="left"
          style="padding: 20px 0 20px 24px">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="领用人" prop="useName">
                <el-input v-model="form.useName" placeholder="请输入领用人姓名" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="领用时间" prop="receiveTime">
                <el-date-picker clearable v-model="form.receiveTime" type="date" value-format="YYYY-MM-DD"
                  placeholder="请选择领用时间" :default-value="new Date()" style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="领用部门" prop="deptId">
                <el-tree-select v-model="form.deptId" :data="deptTree" placeholder="请选择申请部门"
                  :props="{ label: 'label', value: 'id', children: 'children' }" check-strictly filterable
                  :default-expand-all="true" style="width: 100%" @visible-change="handleVisibleChange" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="类别" prop="type">
                <el-select v-model="form.type" :empty-values="[null, undefined]" placeholder="请选择类别"
                  style="width: 100%">
                  <el-option v-for="item in adm_item_type" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="物品名称" prop="itemId">
                <el-tree-select v-model="form.itemId" :data="filteredItemTree" placeholder="请先选择类别"
                  :props="{ label: 'label', value: 'id', children: 'children', disabled: 'disabled' }" check-strictly
                  filterable :default-expand-all="true" style="width: 100%" @change="handleItemChange"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="领用数量" prop="amount">
                <el-input v-model="form.amount" placeholder="请输入领用数量" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="单位" prop="unit">
                <el-input v-model="form.unit" placeholder="请输入单位" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="用途" prop="purpose">
                <el-input v-model="form.purpose" placeholder="请输入用途" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" :rows="3" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加审核流程相关组件 -->
    <ApprovalFlow v-model:visible="auditDialogVisible" :business-type="'ADM-ITEM-RECEIVE-AUDIT'"
      :business-id="Number(currentAuditId)" title="公章管理审核流程" @confirm="handleApprovalFlowConfirm"
      @cancel="handleApprovalFlowCancel" @template-imported="handleTemplateImported" />
  </div>
</template>

<script setup name="AdmItemReceive" lang="ts">
import { listAdmItemReceive, getAdmItemReceive, delAdmItemReceive, addAdmItemReceive, updateAdmItemReceive, getItemTree } from '@/api/general/administration/item/receive/index';
import { AdmItemReceiveVO, AdmItemReceiveQuery, AdmItemReceiveForm, ItemTreeNode } from '@/api/general/administration/item/receive/types';
import type { DeptTreeNode } from '@/api/general/administration/seal/types';
import { getDeptTree } from '@/api/general/administration/seal';
import { useUserStore } from '@/store/modules/user';
import { AdmItemApplyVO } from '@/api/general/administration/item/apply/types';
import { queryAllItem } from '@/api/general/administration/item/store';
import { AdmItemStoreVO } from '@/api/general/administration/item/store/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const admItemReceiveList = ref<AdmItemReceiveVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const admItemReceiveFormRef = ref<ElFormInstance>();

// 查询参数初始化
const select_item_list = ref<AdmItemStoreVO[]>([]);

// 部门树初始化
const deptTree = ref<DeptTreeNode[]>([]);
const deptTreeSelectRef = ref();

// 物品树初始化
const itemTree = ref<any[]>([]);
// 根据选择类型过滤后的树
const filteredItemTree = ref<any[]>([]);

// 用户信息
const userStore = useUserStore();

// 引入数据字典
const { adm_item_type, approval_record_status } = toRefs<any>(proxy?.useDict('adm_item_type', 'approval_record_status'));

// 时间选择器查询参数初始化
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const createTimeRange = ref<[DateModelType, DateModelType]>(['', '']);

// 初始化审核模块
const auditDialogVisible = ref(false);
const currentAuditId = ref<string | number>('');
const itemAuditRef = ref();
const router = useRouter();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 本地时间格式化函数
const formatLocalDate = (date = new Date()) => {
  const padZero = num => String(num).padStart(2, '0');
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`;
};

const initFormData: AdmItemReceiveForm = {
  id: undefined,
  useId: userStore.userId,
  useName: userStore.name,
  receiveTime: formatLocalDate(),
  deptId: undefined,
  type: undefined,
  itemId: undefined,
  itemName: undefined,
  amount: undefined,
  unit: undefined,
  purpose: undefined,
  remark: undefined,
  status: 0,
  approverIdea: undefined,
}
const data = reactive<PageData<AdmItemReceiveForm, AdmItemReceiveQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    useId: undefined,
    deptId: undefined,
    type: undefined,
    itemId: undefined,
    itemName: undefined,
    amount: undefined,
    unit: undefined,
    purpose: undefined,
    status: undefined,
    approverIdea: undefined,
    params: {
    }
  },
  rules: {
    // 领用人id
    useName: [
      { required: true, message: '请输入领用人名称', trigger: 'change' }
    ],
    // 日期（必填，需为合法日期）
    receiveTime: [
      {
        required: true,
        message: '请选择申请日期',
        trigger: 'change',
        validator: (_, value, callback) => {
          if (!value) callback(new Error('请选择日期'));
          else if (isNaN(new Date(value).getTime())) callback(new Error('日期格式无效'));
          else callback();
        }
      }
    ],
    // 领用部门id
    deptId: [
      { required: true, message: '请选择申请部门', trigger: 'change' }
    ],
    // 物品名称（必填，1-50字符）
    itemId: [
      { required: true, message: '请输入物品名称', trigger: 'blur' }
    ],
    // 类别（必填，只能是两种选项之一）
    type: [
      {
        required: true,
        message: '请选择类别',
        trigger: 'change',
        validator: (_, value, callback) => {
          const validTypes = ['0', '1'];
          if (!validTypes.includes(value)) {
            callback(new Error(`类别必须是${validTypes.join('或')}`));
          } else {
            callback();
          }
        }
      }
    ],
    // 数量（必填，必须为大于0的整数）
    amount: [
      { required: true, message: '请输入数量', trigger: 'blur' },
      {
        pattern: /^\d+(\.\d+)?$/,
        message: '必须为数字',
        trigger: 'blur'
      }
    ],
    // 单位（必填）
    unit: [
      { required: true, message: '请输入单位', trigger: 'change' }
    ],
    // 用途（必填）
    purpose: [
      { required: true, message: '请输入用途', trigger: 'change' }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询物品领用列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        bUseTime: dateRange.value[0]?.toString(),
        eUseTime: dateRange.value[1]?.toString()
      };
    }
    if (createTimeRange.value?.length === 2) {
      params.params = {
        ...params.params,
        beginTime: createTimeRange.value[0]?.toString(),
        endTime: createTimeRange.value[1]?.toString()
      };
    }
    const res = await listAdmItemReceive(params);
    admItemReceiveList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  admItemReceiveFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  createTimeRange.value = ['', ''];
  queryFormRef.value?.resetFields();
    // 清空查询参数
  queryParams.value = {
    ...queryParams.value, // 保持结构
    params: {
      bUseTime: undefined,
      eUseTime: undefined,
      beginTime: undefined,
      endTime: undefined,
    },
    itemId: undefined, // ⚡ itemId 应该在这里清空
  };
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AdmItemReceiveVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加物品领用申请";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: AdmItemReceiveVO) => {
  if (row.status != 0) {
    ElMessage.error("只能对未审核的申请进行修改")
  } else {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getAdmItemReceive(_id);
    openDialog(res.data);
    dialog.visible = true;
    dialog.title = "修改物品领用申请";
  }
}

/** 提交按钮 */
const submitForm = () => {
  admItemReceiveFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAdmItemReceive(form.value).finally(() => buttonLoading.value = false);
      } else {
        console.log("form.value", form.value);
        await addAdmItemReceive(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: AdmItemReceiveVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除物品领用编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delAdmItemReceive(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/admItemReceive/export', {
    ...queryParams.value
  }, `admItemReceive_${new Date().getTime()}.xlsx`)
}

// 对话框打开时滚动到顶部
const handleDialogOpen = async () => {
  await nextTick(); // 确保 DOM 渲染完成
  // 使用 document.querySelector 精准获取 Teleport 后的 el-dialog__body
  const scrollBody = document.querySelector<HTMLElement>('.seal-dialog .el-dialog__body');
  if (scrollBody) {
    scrollBody.scrollTop = 0; // 滚动到顶部
  } else {
    console.warn('未找到 el-dialog__body');
  }
};

// 获取部门树
const fetchDeptTree = async () => {
  try {
    const res = await getDeptTree();
    const processNode = (node: any) => {
      if (node.children && node.children.length > 0) {
        // 有子节点 → 禁用，但允许展开
        node.disabled = true;
        node.children.forEach(processNode); // 递归处理子节点
      } else {
        // 叶子节点 → 可选
        node.disabled = false;
      }
    };
    if (Array.isArray(res.data)) {
      res.data.forEach(processNode);
    }
    deptTree.value = res.data;
  } catch (error) {
    console.error('获取部门树失败:', error);
    proxy?.$modal.msgError('获取部门树失败');
  }
};

// 获取物品树
const fetchItemTree = async () => {
  const res = await getItemTree(); // 从接口获取完整物品数据
  // 按 type 分类构建根节点
  const groupedTree = [
    { id: 'root-0', label: '办公用品', children: [] },
    { id: 'root-1', label: '烟酒', children: [] }
  ];
  res.data.forEach((item: any) => {
    const node = {
      id: item.id,
      label: item.itemName,
      type: item.type,
      unit: item.unit,
      children: []
    };
    if (Number(item.type) === 0) groupedTree[0].children.push(node);
    else if (Number(item.type) === 1) groupedTree[1].children.push(node);
  });
  itemTree.value = groupedTree;
  filteredItemTree.value = []; // 默认不显示任何物品
};


// 下拉框打开时展开全部节点
const handleVisibleChange = (visible: boolean) => {
  if (visible) {
    // 展开全部节点（treeSelect 内部的 tree 是 el-tree 实例）
    setTimeout(() => {
      const tree = deptTreeSelectRef.value?.$refs?.tree;
      tree?.expandAll?.();
    }, 0);
  }
};

// 日期date转换string方法
function formatDate(str?: string | Date) {
  if (!str) return undefined;
  const date = typeof str === 'string' ? new Date(str) : str;
  const y = date.getFullYear();
  const m = (date.getMonth() + 1).toString().padStart(2, '0');
  const d = date.getDate().toString().padStart(2, '0');
  return `${y}-${m}-${d}`;
}

// 打开弹窗数据处理
const openDialog = (data?: AdmItemReceiveForm) => {
  if (data) {
    // 回显数据时，做类型和日期转换
    Object.assign(form.value, {
      ...data,
      // type 必须是字符串，保证 ElSelect 正确显示
      type: data.type !== undefined ? String(data.type) : undefined,
      // storeTime 转为 Date 对象（如果你使用 ElDatePicker）
      receiveTime: formatDate(data.receiveTime),
    });
  } else {
    // 新增时重置表单
    reset();
  }
};

// 监听类型选择，动态过滤物品树并清空物品名称（除回显时）
watch(() => form.value.type, (newType, oldType) => {
  if (newType === null || newType === undefined) {
    filteredItemTree.value = [];
    return;
  }
  // 过滤物品树，只保留匹配类型的子节点
  filteredItemTree.value = itemTree.value
    .map(group => {
      const matchedChildren = group.children.filter(c => c.type === Number(newType));
      if (matchedChildren.length === 0) return null;
      return {
        ...group,
        disabled: true,
        children: matchedChildren.map(c => ({ ...c, disabled: false }))
      };
    })
    .filter(Boolean);
    console.log('filteredItemTree', filteredItemTree.value);
  // 如果不是回显（即 oldType 存在且和 newType 不同），则清空物品名称
  if (oldType !== undefined && newType !== oldType) {
    form.value.itemId = undefined;
  }
});

const hasFinalPermission = computed(() => {
  const permissions = useUserStore().permissions;
  return permissions.includes('administration:seal:final');
});

/** 部门审核按钮操作 */
const handleAudit = (row: AdmItemApplyVO) => {
  currentAuditId.value = row.id;
  auditDialogVisible.value = true;
  itemAuditRef.value?.openDialog(row.id, 'dept');
};

/** 董办审核按钮操作 */
const handleFinalAudit = (row: AdmItemApplyVO) => {
  currentAuditId.value = row.id;
  auditDialogVisible.value = true;
  itemAuditRef.value?.openDialog(row.id, 'ceo');
};

/**
 * 审核流程相关处理
 */
const handleApprovalFlowConfirm = (data: any) => {
  ElMessage.success('项目计划提交成功');
  auditDialogVisible.value = false;
  router.back();
};


const handleApprovalFlowCancel = () => (auditDialogVisible.value = false);

const handleTemplateImported = (data: any) => {
  ElMessage.success(`审核模板"${data.templateName}"导入成功`);
};

// 物品选择变化时
const handleItemChange = (selectedId: number | string) => {
  if (!selectedId) {
    form.value.unit = "";
    return;
  }
  const selectedItem = findItemNode(itemTree.value, selectedId);
  if (selectedItem && selectedItem.unit) {
    form.value.unit = selectedItem.unit;
  } else {
    form.value.unit = "";
  }
};

// 递归查找树节点
function findItemNode(tree: any[], id: number | string): any {
  for (const node of tree) {
    if (node.id === id) return node;
    if (node.children && node.children.length > 0) {
      const found = findItemNode(node.children, id);
      if (found) return found;
    }
  }
  return null;
}

// 获取物品列表
const fetchItemList = async () => { 
  try {
    const res = await queryAllItem();
    select_item_list.value = res.data;
  } catch (error) {
    console.error('获取物品列表失败', error);
  }
};


onMounted(() => {
  getList();
  fetchDeptTree();
  fetchItemTree();
  fetchItemList();
});
</script>
<style scoped>
.seal-dialog :deep(.el-dialog__header) {
  text-align: center;
}

/* 合同对话框中的用户选择器样式 */
.user-selector-container {
  width: 100%;
}

.user-selector-container .selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
  min-height: 20px;
}

/* 对话框样式优化 */
:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto !important;
  display: block;
  /* 确保是块级元素 */
}
</style>